package com.pumpkin.annotationdemo.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 通过反射动态的创建对象
 */
public class Test08 {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, NoSuchFieldException {
        Class c1 = Class.forName("com.pumpkin.annotationdemo.reflection.User");
        //构造一个对象
        // User user = (User) c1.newInstance();
        // //本质是调用了无参构造
        // System.out.println(user);

        //通过构造器构建一个对象
        // Constructor declaredConstructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
        // User user2 = (User) declaredConstructor.newInstance("pumpkin", 1, 20);
        // System.out.println(user2);

        //通过反射获取一个方法
        User user3 = (User) c1.newInstance();
        Method setName = c1.getDeclaredMethod("setName", String.class);
        //invoke:激活的意思
        setName.invoke(user3,"hello");
        System.out.println(user3.getName());

        //通过反射操作属性
        User user4 = (User) c1.newInstance();
        Field name = c1.getDeclaredField("name");
        //不能直接操作私有属性，需要关闭程序的安全检测，属性或者方法的setAccessible(true)
        name.setAccessible(true);
        name.set(user4,"world");
        System.out.println(user4.getName());
    }
}
